<?php

namespace interface\v1;

use verify;

class loginStoreClass extends index
{
	
	/**
	 * 小程序登录(可通过openId转userId间接登录  https://developer.work.weixin.qq.com/document/path/90202)
	 */
	public function weChatLogin()
	{
		$code   = $this->post('code');
		$source = $this->header['Source'];
		switch ($source) {
			case 'crm';
				$appid  = para('wxCrmAppid');
				$secret = para('wxCrmAppSecret');
				break;
			case 'erp';
				$appid  = para('wxErpAppid');
				$secret = para('wxErpAppSecret');
				break;
			default;//OA
				$appid  = para('wxOaAppid');
				$secret = para('wxOaAppSecret');
				break;
		}
		
		$result = json_decode(self::curlGet("https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code"), true);
		if (!isset($result['openid']) || empty($result['openid'])) {
			$this->resp['warn'] = $result['errmsg'];
		} else {
			$openid = $result['openid'];
			$token  = match ($source) {
				'crm'   => wechatToken('crmAccessToken'),
				'erp'   => wechatToken('erpAccessToken'),
				default => wechatToken('oaAccessToken'),
			};
			if (empty($code)) {
				$this->resp['warn'] = '未找到code';
			} elseif (empty($token)) {
				$this->resp['warn'] = '未找到token';
			} else {
				$url    = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token={$token}";
				$result = json_decode(self::curlPost($url, json_encode(['openid' => $openid], 320), build: false), true);
				if ($result['errcode'] != 0) {
					$this->resp['warn'] = $result['errmsg'];
				} else {
					$user = query('user', " weChatUserId= '{$result['userid']}'");
					if (empty($user['uid'])) {
						$this->resp['warn'] = '登录失败，请在后台绑定企业微信ID';
					} else {
						$logText    = match ($source) {
							'crm'   => $user['name'] . '登录成功【CRM-小程序】-微信端',
							'erp'   => $user['name'] . '登录成功【ERP-小程序】-微信端',
							default => $user['name'] . '登录成功【OA-小程序】-微信端',
						};
						$this->code = 1;
						$token      = md5s($user['stid']);
						(int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
						$expireTime = 60 * 60 * $expireTime;
						$this->rSet($token, $user['stid'], $expireTime); // 设置redis
						$this->resp['data']['token'] = $token;
						$this->logText(["type" => 'my', "text" => $logText], true);
					}
				}
			}
		}
	}
	
	/**
	 * 账号密码登录
	 */
	public function login()
	{
		$data = [
			'userName' => $this->post['userName'] ?? '',
			'password' => $this->post['password'] ?? '',
			'source'   => $this->post['source'] ?? '',
		];
		// 注释
		$annotation = [
			'userName' => '用户名或手机号',
			'password' => '密码',
			'source'   => '来源',
			// 'deviceID'   => '设备ID',
		];
		// 规则
		$rules = [
			'userName' => 'required',
			'password' => 'required|min_len:6,max_len:20',
			'source'   => 'required',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($data, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
		} else {
			$source = $data['source'];
			unset($data['source']);
			$user = query('user', " userName = '{$data['userName']}' ");
			if (self::isNull($user['uid']) || verifyPwd($data['password'], $user['password']) !== true) {
				$this->resp['warn'] = '登录失败，账号密码输入错误';
			} else {
				$token = md5s($user['stid']);
				(int)$expireTime = para('expireTime') ?? 2; //登录有效期，单位小时
				$expireTime = 60 * 60 * $expireTime;
				$this->rSet($token, $user['stid'], $expireTime); // 设置redis
				$this->resp['data'] = [
					'token' => $token,
				];
				
				
				$logText    = match ($source) {
					'crm'        => $user['name'] . '登录成功【CRM小程序】-token',
					'erp'        => $user['name'] . '登录成功【ERP小程序】-token',
					'pda', 'PDA' => $user['name'] . '登录成功【ERP-PDA】-userId',
					default      => $user['name'] . '登录成功【OA小程序】-token',
				};
				$this->code = 1;
				$this->logText(["type" => 'my', "text" => $logText], true);
			}
		}
	}
}
